package com.liuhan.house.controller;

import com.github.pagehelper.PageInfo;
import com.liuhan.house.common.Constants;
import com.liuhan.house.common.ServerResponse;
import com.liuhan.house.pojo.Community;
import com.liuhan.house.pojo.House;
import com.liuhan.house.pojo.User;
import com.liuhan.house.service.CommunityService;
import com.liuhan.house.service.FileService;
import com.liuhan.house.service.HouseService;
import com.liuhan.house.service.UserService;
import com.liuhan.house.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Controller
public class HouseController {
    @Autowired
    private HouseService houseService;
    @Autowired
    private UserService userService;

    @Autowired
    private CommunityService communityService;

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private FileService fileService;


    /**
     * 跳转到房屋详情页
     */
    @RequestMapping("page/detail")
    public String pageDetail() {
        return "/house/detail";
    }

    /**
     * 获取房屋列表
     */
    @RequestMapping("house/list")
    public String getHouseList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "2") int pageSize,
                               @RequestParam("orderBy") String orderBy, @RequestParam("keyword") String keyword,
                                @RequestParam("type") Integer type,
                               HttpServletRequest request, ModelMap modelMap) {

        PageInfo<House> houseList = houseService.getHouseListByKeyWord(keyword, orderBy, type, pageNum, pageSize);
        modelMap.put("orderBy",orderBy);
        modelMap.put("type", type);
        modelMap.put("keyword", keyword);
        modelMap.put("pageInfo", houseList);
        return "/house/listing";
    }

    /**
     * 房屋明细查询
     * @param houseId
     * @return
     */
    @RequestMapping("house/detail")
    public String houseDetail(@RequestParam(value = "houseId") int houseId, ModelMap modelMap) {
        // 查询房屋详情
        House house = houseService.selectByHouseId(houseId);
        String imgs = house.getHouseImages();
        String[] img = imgs.split(",");
        modelMap.put("house", house);
        modelMap.put("img", img);
        // 查询经纪人详情
        User agency = userService.getInfoById(house.getUserId());
        modelMap.put("agency", agency);
        return "/house/detail";
    }

    /**
     * 给经纪人发送邮件
     */
    @RequestMapping("send/email/to/agency")
    public String sendEmailToAgency(HttpServletRequest request) {
        String username = request.getParameter("userName");
        String email = request.getParameter("email");
        String msg = request.getParameter("msg");
        String toEmail = request.getParameter("toEmail");

        String title = "收到来自姓名为：" + username + "邮件账号为：" + email + "的内容留言";
        String text = msg;
        sendMail(text, toEmail ,title);
        return "success/success";

    }

    // 发送邮件
    private void sendMail(String text, String userEmail, String title) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(userEmail);
        mailMessage.setText(text);
        mailMessage.setSubject(title);
        javaMailSender.send(mailMessage);
    }


    /**
     * 添加房屋信息
     */
    @RequestMapping("page/addHouse")
    public String addHouse(ModelMap modelMap, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/user/accounts/login";
        }
        // 查询城市和小区名称

        List<Community> communities = communityService.getAll();
        ArrayList<Community> collect = communities.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getCityName()))), ArrayList::new));
        modelMap.put("communities", collect);
        return "/house/add";
    }

    /**
     * 添加房屋
     */
    @PostMapping("house/add")

    public String addHouse(House house, @RequestParam(value = "houseFiles", required = false) MultipartFile file, HttpServletRequest request) {
        // 图片上传到地址服务器
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = fileService.upload(file, path);
        String url = PropertiesUtil.getProperty("FTP_SERVER_HTTP_PREFIX") + targetFileName;
        house.setHouseImages(url);
        User user = (User) request.getSession(true).getAttribute(Constants.USER_ATTRIBUTE);
        int result = houseService.addHouse(house, user);
        if (result > 0) {
            return "redirect:/page/user/profile";
        }
        return "";
    }

    /**
     * 根据用户标识查询代理房屋
     */
    @RequestMapping("house/getByUserId")
    public String getByUserId(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Constants.USER_ATTRIBUTE);
        List<House> houseList = houseService.getByUserId(user.getUserId());
        modelMap.addAttribute("houseList", houseList);
        return "house/ownlist";
    }

    /**
     * 删除房屋信息
     */
    @RequestMapping("house/deleteByHouseId")
    @ResponseBody
    public ServerResponse deleteByHouseId(@RequestParam("houseId") Integer houseId) {
        int result = houseService.deleteById(houseId);
        if (result >0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        } else {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }


}
